﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DBMS.Models;
using DBMS.Models.DataInterfaces;
using System.IO;
using System.Windows.Forms;

using DBMS.Helpers.Application;
using DBMS.Helpers.Metadata;

namespace DBMS.Data
{
    public class DatabaseRepository : IDatabaseRepository
    {
        public static int CurrentDatabaseID { get; set; }

        public Database GetDatabase(int databaseId)
        {
            SetCurrentDirectoryToAppDir();
            CurrentDatabaseID = databaseId;
            return new MetadataManager().GetDatabase(databaseId);
        }

        public void Update(Database database)
        {
            MetadataManager mg = new MetadataManager();
            mg.UpdateDatabase(database);
        }

        public void Delete(int databaseId)
        {
            SetCurrentDirectoryToAppDir();
            throw new NotImplementedException();
        }

        public IList<Database> GetAll()
        {
            SetCurrentDirectoryToAppDir();
            IList<Database> databases = new List<Database>();
            MetadataManager metaDataManager = new MetadataManager(); 

            foreach (String path in Directory.GetDirectories(Configuration.Instance.WorkingDirectory))
            {
                string[] parts = path.Split('\\');
                databases.Add(metaDataManager.GetDatabase(Convert.ToInt32(parts[parts.Length - 1])));
            }

            return databases;
        }

        private void SetCurrentDirectoryToAppDir()
        {
            string currDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
            Directory.SetCurrentDirectory(currDir);
        }

        private void SetCurrentDirectoryToServerDir()
        {
            string currDir = Path.GetDirectoryName(Application.ExecutablePath);
            Directory.SetCurrentDirectory(currDir);
        }

        private void SetCurrentDirectoryToDatabaseDir(int databaseId)
        {
            Directory.SetCurrentDirectory(databaseId.ToString());
        }

        public int CreateDatabase(Database database)
        {
            foreach (Database db in GetAll())
            {
                if (db.Name.Equals(database.Name))
                {
                    throw new Exception("Duplicate name for database: " + db.Name);
                }
            }

            SetCurrentDirectoryToAppDir();
            int dbId = Directory.GetDirectories(Configuration.Instance.WorkingDirectory).Length + 1;
            Directory.CreateDirectory(Configuration.Instance.WorkingDirectory + "//" + dbId.ToString());

            database.Index = dbId;
            new MetadataManager().CreateDatabase(database);
            return database.Index;
        }
    }
}
